﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using hotel.Win.BaseData;
using hotel.DAL;
using hotel.Common;
using hotel.Win.Common;
using System.Data.Common;
using hotel.Win.Report;

namespace hotel.Win.Subscribe
{
    /// <summary>
    /// 客人费用维护
    /// </summary>
    public partial class krfyMaintain : Form
    {
        hotelEntities _context;
        RZJL rzjlModel;
        ROOM roomModel;
        bool isAdd;
        bool isPrint;//是否已经打印
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rzzh">入住帐号</param>
        public krfyMaintain(string rzzh)
        {            
            InitializeComponent();
            isPrint = false;
            //btntf.Visible = !(Application.OpenForms[Application.OpenForms.Count - 1] is jztfFrm);
            isAdd = false;
            _context = MyDataContext.GetDataContext;
            cobxfl.DisplayMember = "FLMC";
            cobxfl.ValueMember = "ID";
            cobxfl.DataSource = _context.XFXMFL.AsNoTracking().OrderBy(p => p.FLMC).ToList();
            
            rzjlModel = _context.RZJL.Find(rzzh);
            roomModel = rzjlModel.ROOM;
            txtxfsl.Value = 1;
            var rzryModel = _context.RZRY.AsNoTracking().Where(p => p.RZJL.ID == rzjlModel.ID).FirstOrDefault();
            if (rzryModel == null)
                rzryModel = new RZRY() { KRXM = "" };
            gboxfyjl.Text = "房间号[" + roomModel.ID + "]客人[" + rzryModel.KRXM + "]的费用清单";
            var qry= _context.XFXM.AsNoTracking().Where(p => p.KXF == "是").OrderBy(p => p.MC);
            gridxm.DataSource = qry.ToList();
            if (gridxm.Rows.Count > 0)
                gridxm_CellClick(gridxm, null);
            BindGrid();
            btnprint.Visible = false;
            if (roomModel.ID == SysConsts.Room9999)
            {
                btnxftd.Enabled = false;
                btnxfzd.Enabled = false;
                btnprint.Enabled = true;
                btnprint.Visible = true;
            }
        }

        private void BindGrid()
        {
            var qry =  from q in _context.XFJL
                                  where q.RZJL.ID == rzjlModel.ID && q.XFXM_MC != "押金"
                                  orderby q.CJRQ
                                  select new
                                  {
                                      q.CJRQ,
                                      q.CJRY,
                                      q.JE,
                                      q.SL,
                                      q.DJ,
                                      q.XFXM_MC,
                                      q.ID,
                                      q.BZSM
                                  };            
            gridmain.DataSource = qry.ToList();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (roomModel.ID == SysConsts.Room9999 && isPrint == false && gridmain.Rows.Count > 0
                && MessageBox.Show("你还没有打印，是否退出，退出后不能再打印", "打印提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                return;
            
            this.Close();
        }

        /// <summary>
        /// 退单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnxftd_Click(object sender, EventArgs e)
        {
            string XFID = Common.ControlsUtility.GetActiveGridValue(gridmain, "XFID");
            if (XFID == "")
            {
                MessageBox.Show("请选择一个消费记录!");
                return;
            }
            if (Convert.ToInt32(Common.ControlsUtility.GetActiveGridValue(gridmain, "XFSL")) < 0)
            {
                MessageBox.Show("你选择的消费记录，已经是退单记录，操作失败!");
                return;
            }
            int id = Convert.ToInt32(XFID);
            var oldxfjlModel = _context.XFJL.First(p => p.ID == id);

            var frm = new krfytdMaintain(oldxfjlModel);
            if (frm.ShowDialog() != DialogResult.OK)
                return;

            var xfjlModel = new XFJL();
            xfjlModel.CJRQ = DateTime.Now;
            xfjlModel.CJRY = UserLoginInfo.FullName;
            xfjlModel.DJ = oldxfjlModel.DJ;
            xfjlModel.SL = -frm.TDSL;
            xfjlModel.JE = -(xfjlModel.DJ * frm.TDSL);
            xfjlModel.ROOM = roomModel;
            xfjlModel.RZJL = rzjlModel;
            xfjlModel.XFXM = oldxfjlModel.XFXM;
            xfjlModel.XFXM_MC = oldxfjlModel.XFXM.MC + "(退)";
            xfjlModel.XFBZ = "消";
            xfjlModel.BZSM = "退单";
            xfjlModel.YJ = 0;
            _context.XFJL.Add(xfjlModel);
            _context.SaveChanges();
            BindGrid();
            isAdd = true;
            #region 日志纪录             
            var logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.消费退单;
            logInfo.Type = LogTypeEnum.涉及金额;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message ="消费项目:" + xfjlModel.XFXM.MC + ",金额:" + xfjlModel.JE;
            logInfo.Save();
            #endregion
        }

        /// <summary>
        /// 消费转单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnxfzd_Click(object sender, EventArgs e)
        {
            string XFID = Common.ControlsUtility.GetActiveGridValue(gridmain, "XFID");
            if (XFID == "")
            {
                MessageBox.Show("请选择一个消费记录!");
                return;
            }
            if (Convert.ToInt32(Common.ControlsUtility.GetActiveGridValue(gridmain, "XFSL")) < 0)
            {
                MessageBox.Show("你选择的消费记录，已经是退单记录，操作失败!");
                return;
            }
            int id = Convert.ToInt32(XFID);
            var xfjlModel = _context.XFJL.First(p => p.ID == id);

            var frm = new krfyzzMaintain(xfjlModel);
            if (frm.ShowDialog() != DialogResult.OK)
                return;
            if (frm.RoomID == roomModel.ID)
                return;
            var mb_rzjl = _context.RZJL.Where(p => p.ROOM.ID == frm.RoomID).FirstOrDefault();
            if (mb_rzjl == null)
            {
                MessageBox.Show("目标房间号" + frm.RoomID + ",不存在或没人入住");
                return;
            }
            xfjlModel.ROOM = mb_rzjl.ROOM;
            xfjlModel.RZJL = mb_rzjl;
            xfjlModel.BZSM = "从" + roomModel.ID + "房间转入";
            _context.SaveChanges();
            MessageBox.Show("消费转帐成功！");
            isAdd = true;
            #region 日志纪录
            var logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.消费转单;
            logInfo.Type = LogTypeEnum.涉及金额;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "新房号:" + frm.RoomID + "，项目:" + xfjlModel.XFXM.MC + ",金额:" + xfjlModel.JE;
            logInfo.Save();
            logInfo.RoomId = mb_rzjl.ROOM_ID;
            logInfo.Rzid = mb_rzjl.ID;
            logInfo.Message = "原房号:" + rzjlModel.ROOM_ID+ "，项目:" + xfjlModel.XFXM.MC + ",金额:" + xfjlModel.JE;
            logInfo.Save();
            #endregion
            BindGrid();
        }

        private void btnadd_Click(object sender, EventArgs e)
        {
            string XMID = Common.ControlsUtility.GetActiveGridValue(gridxm, "XMID");
            if (XMID == "")
                return;
            if (txtdj.Value <= 0)
            {
                MessageBox.Show("必须输入单价，才能正常增加！");
                return;
            }
            //大于押金总额的提醒

            int id = Convert.ToInt32(XMID);
            var xfxmModel = _context.XFXM.First(p => p.ID == id);
            var xfjlModel = new XFJL();
            xfjlModel.XFXM_ID = id;
            xfjlModel.RZJL_ID = rzjlModel.ID;
            xfjlModel.ROOM_ID = roomModel.ID;            
            xfjlModel.CJRQ = DateTime.Now;
            xfjlModel.CJRY = UserLoginInfo.FullName;
            xfjlModel.DJ = txtdj.Value;
            xfjlModel.SL = (int)txtxfsl.Value;
            xfjlModel.JE = xfjlModel.DJ * xfjlModel.SL;
            xfjlModel.ZFFS = "人民币";
            xfjlModel.XFBZ = "消";
            xfjlModel.XFXM_MC = xfxmModel.MC;
            xfjlModel.YJ = 0;
            if (roomModel.ID == SysConsts.Room9999)
            {
                xfjlModel.BZSM = "非住房消费";
            }
            _context.XFJL.Add(xfjlModel);
            _context.SaveChanges();
            BindGrid();
            isAdd = true;
            #region 日志纪录
            var logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.消费入单;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "消费项目:" + xfjlModel.XFXM.MC + ",金额:" + xfjlModel.JE;
            logInfo.Save();
            #endregion

        }

        private void cobxfl_SelectedIndexChanged(object sender, EventArgs e)
        {
            string id = cobxfl.SelectedValue.ToString();
            gridxm.AutoGenerateColumns = false;
            gridxm.DataSource = _context.XFXM.AsNoTracking().Where(p => p.XFXMFL.ID == id && p.KXF == "是").OrderBy(p => p.MC).ToList();
        }

        private void txtdm_TextChanged(object sender, EventArgs e)
        {
            //string esql = "select a.DM,a.MC,a.DJ,a.YWMC,a.ID from XFXM as a where a.KXF ='是' and  a.YWMC like @ywmc order by mc";

           // ObjectParameter op = new ObjectParameter("ywmc", "%" + txtdm.Text.Trim() + "%");
           // ObjectQuery<DbDataRecord> query = _context.CreateQuery<DbDataRecord>(esql, op);
            var ywmc = txtdm.Text.Trim();
            gridxm.DataSource = _context.XFXM.AsNoTracking().Where(p => p.KXF == "是" && p.YWMC.Contains(ywmc)).ToList();
            if (gridxm.Rows.Count > 0)
                gridxm_CellClick(gridxm, null);
        }

        private void gridxm_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string dj = Common.ControlsUtility.GetActiveGridValue(gridxm, "XMDJ");
            if (string.IsNullOrEmpty(dj))
                return;
            txtdj.Value = Convert.ToDecimal(dj);
        }

        private void krfyMaintain_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                //非住房消费直接结算，不等夜审
                if (roomModel.ID == SysConsts.Room9999)
                {
                    foreach (var item in _context.XFJL.Where(p => p.RZJL_ID == SysConsts.Room9999RZID))
                    {
                        var xfxmArcModel = new XFJL_ARC { RZJL_ID = item.RZJL_ID, ROOM_ID = item.ROOM_ID };
                        xfxmArcModel.ID = item.ID;
                        xfxmArcModel.CJRQ = item.CJRQ;
                        xfxmArcModel.CJRY = item.CJRY;
                        xfxmArcModel.DJ = item.DJ;
                        xfxmArcModel.SL = item.SL;
                        xfxmArcModel.JE = item.JE;
                        xfxmArcModel.ZFFS = item.ZFFS;
                        xfxmArcModel.XFXM_MC = item.XFXM_MC;
                        xfxmArcModel.XFXM_ID = item.XFXM_ID;
                        xfxmArcModel.XFBZ = "消";
                        xfxmArcModel.BZSM = item.BZSM;
                        _context.XFJL_ARC.Add(xfxmArcModel);
                        _context.Entry(item).State = EntityState.Deleted;
                    }
                    _context.SaveChanges();
                }
                this.DialogResult = isAdd ? DialogResult.OK : DialogResult.Cancel;
            }
            catch (Exception ex )
            {
                var _log = new Log4NetLog();
                _log.Error("krfyMaintain_FormClosed", ex);
            }
        }

        private void btnprint_Click(object sender, EventArgs e)
        {
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.打印;
            logInfo.Type = LogTypeEnum.一般操作;
            logInfo.Message = "非住房消费";
            logInfo.Rzid = SysConsts.Room9999RZID;
            logInfo.RoomId = SysConsts.Room9999;
            ReportEntry.ShowFeiXiaoFeiMingXiBill(logInfo);
            isPrint = true;
        }
    }
}
